import 'package:casdon/modules/recipe/data/model/recipe_banner_model.dart';
import 'package:casdon/modules/recipe/domain/states/recipe_banner_list_state.dart';
import 'package:casdon/modules/recipe/domain/usecase/recipe_banner_list_usecase.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class RecipeBannerListNotifier extends AsyncNotifier<RecipeBannerListState> {
  bool _isRefreshing = false;

  @override
  Future<RecipeBannerListState> build() async {
    return _fetchData();
  }

  Future<void> refresh() async {
    if (_isRefreshing) return;
    _isRefreshing = true;
    final previous = state.valueOrNull;

    try {
      final newState = await _fetchData();
      state = AsyncValue.data(newState);
    } catch (e, st) {
      if (previous != null) {
        state = AsyncValue.data(previous);
      } else {
        state = AsyncValue.data(RecipeBannerListState.initial());
      }
    } finally {
      _isRefreshing = false;
    }
  }

  Future<RecipeBannerListState> _fetchData() async {
    final ret = await ref.read(recipeBannerListUsecaseProvider).execute();
    final data = RecipeBannerModel.listFromApi(ret);
    data.sort((a, b) => a.sort.compareTo(b.sort));
    return RecipeBannerListState(data: data);
  }
}

final recipeBannerListNotifierProvider =
    AsyncNotifierProvider<RecipeBannerListNotifier, RecipeBannerListState>(
      () => RecipeBannerListNotifier(),
    );
